package com.mq.work;

import com.mq.config.ConnectUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @author hezhaoxiang
 * @description // work 模型下 消费者 2
 * @date 15:58 2020/9/6
 **/
public class HelloWorldRec2 {
    private final static  String QUEUE_NAME = "HELLO";
    //统计消费消息的数量
    private static int msgCount;

    public static void recMsg() throws URISyntaxException, KeyManagementException, TimeoutException, NoSuchAlgorithmException, IOException {
        //1. 获取连接
        Connection connect = ConnectUtils.getConnect();
        //2. 创建信道
        Channel channel = connect.createChannel();
        // 2.1 设置每次只能先抓取一个，消费完再抓取新的一个
        channel.basicQos(1);
        //3. 创建/获取 队列(如果队列不存在，则创建，反之则直接，参数要与生产者一致)
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //4. 创建消费者

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(java.lang.String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, StandardCharsets.UTF_8);
                System.out.println("[消费者2] 获取消息:" + msg);
                channel.basicAck(envelope.getDeliveryTag(), false);
                try {
                    //休眠 1000毫秒 表示操作间隙
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                msgCount ++;
                //统计消费消息的数量
                System.out.println("[消费者2]消费的消息数量："+msgCount);
            }
        };

        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
    public static void main(String[] args) throws KeyManagementException, TimeoutException, NoSuchAlgorithmException, IOException, URISyntaxException {
        HelloWorldRec2.recMsg();

    }
}
